//
//  CollectionView_runtime.swift
//  MyLibrary
//
//  Created by 周博 on 2020/6/17.
//  Copyright © 2020 ncit. All rights reserved.
//

import UIKit
import MJRefresh


private var UICollectionView_headerRefreshBlock_key: String = "UICollectionView_headerRefreshBlock_key"

private var UICollectionView_footerRefreshBlock_key: String = "UICollectionView_footerRefreshBlock_key"

public extension UICollectionView {

    override open class func initRunTime() {

        // 因为不太好交换init(frame:) 和 init(coder:)方法, 所以取巧交换setDelegate方法
        exchange(originalSelector: #selector(setter: delegate), swizzledSelector: #selector(exchange_delegate(delegate:)))
    }

    @objc func exchange_delegate(delegate: Any) {

        exchange_delegate(delegate: delegate)

        if #available(iOS 11.0, *) {
            /// warning: 默认不计算内边距 (如果计算内边距会导致转场动画的时候 两次的frame不一致 这一统一设置为never, 如果有其他需求 再综合考虑怎么配置这里的通用系)
            contentInsetAdjustmentBehavior = .never
        } else {
            /// Fallback on earlier versions
        }

        keyboardDismissMode = .onDrag
    }


    
    /** 下拉刷新 */
    var headerRefreshBlock: (() -> Void)? {
        get {
            if let headerRefreshBlock = objc_getAssociatedObject(self, &UICollectionView_headerRefreshBlock_key) as? () -> Void {
                return headerRefreshBlock
            } else {
                return nil
            }
        }
        set {
            objc_setAssociatedObject(self, &UICollectionView_headerRefreshBlock_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

            if headerRefreshBlock != nil {
                mj_header = MJRefreshNormalHeader(refreshingBlock: headerRefreshBlock!)
                /// 导航栏下隐藏MJ_header
                mj_header!.isAutomaticallyChangeAlpha = true
            } else {
                mj_header = nil
                print("设置mj_header为nil")
            }
        }
    }
    
    /** 上拉加载更多 */
    var footerRefreshBlock: (() -> Void)? {
        get {
            if let footerRefreshBlock = objc_getAssociatedObject(self, &UICollectionView_footerRefreshBlock_key) as? () -> Void {
                return footerRefreshBlock
            } else {
                return nil
            }
        }
        set {
            objc_setAssociatedObject(self, &UICollectionView_footerRefreshBlock_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

            if footerRefreshBlock != nil {
                mj_footer = MJRefreshBackNormalFooter(refreshingBlock: footerRefreshBlock!)
                
            } else {
                mj_footer = nil
            }
        }
    }
    
    /** 设置刷新的title */
    var headerRefreshTitle: String? {
        get {
            return nil
        } set {
            
            (mj_header as? MJRefreshStateHeader)?.setTitle(newValue ?? "", for: .idle)
        }
    }


}
